package com.kun.kunkunmall.order.web;

import com.kun.common.exception.NoStockException;
import com.kun.kunkunmall.order.service.OrderService;
import com.kun.kunkunmall.order.vo.OrderConfirmVo;
import com.kun.kunkunmall.order.vo.OrderSubmitVo;
import com.kun.kunkunmall.order.vo.SubmitRespVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.util.concurrent.ExecutionException;

@Controller
public class OrderWebController {

    @Autowired
    OrderService orderService;

    /**
     * 跳转到结算页面
     *
     * @return
     */
    @GetMapping("/toTrade")
    public String toTrade(Model model) throws ExecutionException, InterruptedException {
        OrderConfirmVo confirmVo = orderService.confirmOrder();
        model.addAttribute("orderConfirmData", confirmVo);
        return "confirm";
    }

    /**
     * 下单功能
     *
     * @param submitVo 页面提交的订单信息
     * @return
     */
    @PostMapping("/submitOrder")
    public String submitOrder(OrderSubmitVo submitVo, Model model, RedirectAttributes redirectAttributes) {
        // 创建订单，验令牌，验价格，锁库存

        try {
            SubmitRespVo respVo = orderService.submitOrder(submitVo);
            System.out.println(submitVo);
            if (respVo.getCode() == 0) {
                // 下单成功来到支付选择页面
                model.addAttribute("submitOrderResp", respVo);
                return "pay";
            } else {
                // 下单失败回到订单确认页面，重新确认订单信息
                String msg = "";
                switch (respVo.getCode()) {
                    case 1:
                        msg += "订单信息过期，请重新提交";
                        break;
                    case 2:
                        msg += "商品价格发生变化，请确认后再次提交";
                        break;
                    case 3:
                        msg += "商品库存不足";
                        break;
                }
                redirectAttributes.addFlashAttribute("msg", msg);
                return "redirect:http://order.kunkunmall.com/toTrade";
            }
        } catch (Exception e) {
            if (e instanceof NoStockException) {
                String msg = ((NoStockException) e).getMsg();
                redirectAttributes.addFlashAttribute("msg",msg);
            }

            return "redirect:http://order.kunkunmall.com/toTrade";

        }
    }
}
